<template>
  <div class="product-info">
    <h3>填写商品信息</h3>
    
    <el-form
      ref="formRef"
      :model="formData"
      label-width="120px"
      class="product-form"
    >
      <el-form-item label="商品类型" required>
        <el-radio-group v-model="formData.type" disabled>
          <el-radio label="实物商品">实物商品</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="商品名称" required>
        <el-input
          v-model="formData.name"
          placeholder="请输入商品名称，50个字符以内"
          maxlength="50"
          show-word-limit
          clearable
        />
      </el-form-item>

      <el-form-item label="卖点描述">
        <el-input
          v-model="formData.sellingPoint"
          placeholder="商品的卖点信息，展示在商品详情页标题下方，50个字符以内"
          maxlength="50"
          show-word-limit
          clearable
        />
      </el-form-item>

      <el-form-item label="商品品牌" required>
        <el-select
          v-model="formData.brand"
          placeholder="请选择商品品牌"
          clearable
          filterable
          style="width: 100%"
        >
          <el-option
            v-for="brand in brandList"
            :key="brand.id"
            :label="brand.name"
            :value="brand.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="商品关键词">
        <el-input
          v-model="formData.keywords"
          placeholder="请输入商品关键词，60个字符以内"
          maxlength="60"
          show-word-limit
          clearable
        />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商品售价" required>
            <el-input
              v-model="formData.price"
              placeholder="请输入商品售价"
              type="number"
              step="0.01"
              clearable
            >
              <template #append>元</template>
            </el-input>
            <div class="form-tip">浮点数保留2位小数，价格最大不超过9999999.00</div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="市场价">
            <el-input
              v-model="formData.marketPrice"
              placeholder="请输入市场价"
              type="number"
              step="0.01"
              clearable
            >
              <template #append>元</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="配送方式">
        <el-radio-group v-model="formData.deliveryMethod" disabled>
          <el-radio label="商家配送">商家配送</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="商品图片" required>
        <div class="upload-area">
          <el-upload
            v-model:file-list="fileList"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
            :before-upload="beforeImageUpload"
            accept="image/jpeg,image/jpg,image/png"
            :limit="15"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">
            支持格式：jpg、jpeg、png，图片大小不超过2M<br/>
            第一张上传的图片默认为主图，最多可上传15张
          </div>
          <div v-if="fileList.length > 0" class="image-list">
            <div
              v-for="(file, index) in fileList"
              :key="index"
              class="image-item"
            >
              <img :src="file.url" alt="">
              <div class="image-actions">
                <el-button
                  v-if="index !== 0"
                  size="small"
                  @click="setMainImage(index)"
                >
                  设为主图
                </el-button>
                <el-tag v-else type="success" size="small">主图</el-tag>
              </div>
            </div>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="主图视频">
        <el-upload
          action="#"
          :auto-upload="false"
          :on-change="handleVideoChange"
          :before-upload="beforeVideoUpload"
          accept="video/mp4"
          :limit="1"
          :file-list="videoList"
        >
          <el-button type="primary">选择视频</el-button>
        </el-upload>
        <div class="upload-tip">
          1:1/16:9；大小100MB以下；文件格式为MP4
        </div>
      </el-form-item>

      <el-form-item label="商品备注">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="4"
          placeholder="请输入商品备注，200个字符以内"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ref, reactive, watch } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { brandData } from '../../utils/productMock'

export default {
  name: 'ProductInfo',
  components: {
    Plus
  },
  props: {
    modelValue: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const formRef = ref()
    const brandList = ref(brandData)
    const fileList = ref([])
    const videoList = ref([])

    const formData = reactive({
      type: '实物商品',
      name: '',
      sellingPoint: '',
      brand: null,
      keywords: '',
      price: '',
      marketPrice: '',
      deliveryMethod: '商家配送',
      images: [],
      video: null,
      remark: ''
    })

    // 监听props变化
    watch(() => props.modelValue, (newVal) => {
      Object.assign(formData, newVal)
      if (newVal.images && newVal.images.length > 0) {
        fileList.value = newVal.images.map((url, index) => ({
          name: `image-${index}`,
          url: url
        }))
      }
      if (newVal.video) {
        videoList.value = [{ name: 'video', url: newVal.video }]
      }
    }, { immediate: true, deep: true })

    // 监听formData变化，同步到父组件
    watch(formData, (newVal) => {
      emit('update:modelValue', { ...newVal })
    }, { deep: true })

    // 图片上传前验证
    const beforeImageUpload = (file) => {
      const isValidType = ['image/jpeg', 'image/jpg', 'image/png'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isValidType) {
        ElMessage.error('只支持 JPG、JPEG、PNG 格式的图片!')
        return false
      }
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
      }
      return true
    }

    // 图片变化处理
    const handleImageChange = (file, files) => {
      if (file.raw) {
        const reader = new FileReader()
        reader.onload = (e) => {
          fileList.value = files.map(f => ({
            name: f.name,
            url: f.url || e.target.result
          }))
          formData.images = fileList.value.map(f => f.url)
        }
        reader.readAsDataURL(file.raw)
      }
    }

    // 图片移除处理
    const handleImageRemove = (file, files) => {
      fileList.value = files
      formData.images = fileList.value.map(f => f.url)
    }

    // 设置主图
    const setMainImage = (index) => {
      const temp = fileList.value[index]
      fileList.value.splice(index, 1)
      fileList.value.unshift(temp)
      formData.images = fileList.value.map(f => f.url)
      ElMessage.success('主图设置成功')
    }

    // 视频上传前验证
    const beforeVideoUpload = (file) => {
      const isMP4 = file.type === 'video/mp4'
      const isLt100M = file.size / 1024 / 1024 < 100

      if (!isMP4) {
        ElMessage.error('只支持 MP4 格式的视频!')
        return false
      }
      if (!isLt100M) {
        ElMessage.error('视频大小不能超过 100MB!')
        return false
      }
      return true
    }

    // 视频变化处理
    const handleVideoChange = (file) => {
      if (file.raw) {
        const reader = new FileReader()
        reader.onload = (e) => {
          formData.video = e.target.result
          videoList.value = [{ name: file.name, url: e.target.result }]
        }
        reader.readAsDataURL(file.raw)
      }
    }

    return {
      formRef,
      formData,
      brandList,
      fileList,
      videoList,
      beforeImageUpload,
      handleImageChange,
      handleImageRemove,
      setMainImage,
      beforeVideoUpload,
      handleVideoChange
    }
  }
}
</script>

<style scoped>
.product-info {
  padding: 20px;
}

.product-info h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #303133;
}

.product-form {
  max-width: 800px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.upload-area {
  width: 100%;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
  line-height: 1.6;
}

.image-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
  margin-top: 15px;
}

.image-item {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.image-item img {
  width: 100%;
  height: 150px;
  object-fit: cover;
  display: block;
}

.image-actions {
  padding: 8px;
  text-align: center;
  background-color: #f5f7fa;
}
</style>
